package com.tc.zookeeper.curator;

import org.apache.commons.collections.CollectionUtils;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class MetricPathChildrenCacheListener extends EnhancedPathChildrenCacheListener {

	private static Logger LOGGER = LoggerFactory.getLogger(MetricPathChildrenCacheListener.class);

	private Map<String, String> zkChildrenMap;

	private String connStr;

	private String path;

	public MetricPathChildrenCacheListener(String path, String targetConnectString) {
		super();
		this.path = path;
		this.connStr = targetConnectString;

		try {
			EnhancedCuratorFramework client = EnhancedCuratorFrameworkFactory.getStartedClientByConnectString(connStr);
			String version = client.checkExists().forPath(path).getVersion() + "";
			String content = nodesToString(client.getChildren().forPath(path));

			String fullPath = client.getNamespace() + path;
			/*zkChildrenMap = MetricRegister.getZkNodeChildrenMap(fullPath, content, connStr, version);
			MetricRegister.registerChildNodeZkPath(fullPath, zkChildrenMap);*/
		} catch (Exception e) {
			LOGGER.error("MetricPathChildrenCacheListener constructor, " + e.getMessage());
		}
	}

	@Override
	public void childEnhancedEvent(EnhancedCuratorFramework client, PathChildrenCacheEvent event) throws Exception {
		try {
			String data = nodesToString(client.getChildren().forPath(path));
			String version = client.checkExists().forPath(path).getVersion() + "";
			///MetricRegister.updateZkNodeChildrenMap(data, version, zkChildrenMap);
			// LOGGER.info("childEnhancedEvent>>>>>>>>>>version:" + version);
		} catch (Exception e1) {
			LOGGER.error("childEnhancedEvent error:" + e1.getMessage());
		}
	}

	public static String nodesToString(List<String> nodes) {
		if (CollectionUtils.isEmpty(nodes)) {
			return "";
		}

		StringBuilder sb = new StringBuilder();
		Iterator<String> i = nodes.iterator();
		for (;;) {
			String e = i.next();
			sb.append(e);
			if (!i.hasNext()) {
				return sb.toString();
			}
			sb.append(", ");
		}
	}

}
